﻿using System.Web.Mvc;
using System.Web.Security;
using Storytelling.Modelos;
using Storytelling.Models;
using Storytelling.Negocio;
using Storytelling.Negocio.Excecoes;
using System.Web;
using System;
using Storytelling.Entidades;

namespace Storytelling.Controllers
{
    public class AccountController : Controller
    {
        //
        // GET: /Account/LogOn

        public ActionResult LogOn()
        {
            return View();
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(LogarModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                model.Senha = GerenciadorAcesso.Cifrar(model.Senha);

                if (Servicos.Usuario.ValidarUsuario(model))
                {

                    Usuario usuario = Servicos.Usuario.Consultar(model.Login);

                    string roles = "";

                    switch (usuario.Tipo.Value)
                    {
                        case Tipo.Narrador:
                            roles = "Narrador";
                            break;
                        case Tipo.Editor:
                            roles = "Narrador|Editor";
                            break;
                        case Tipo.Administrador:
                            roles = "Narrador|Editor|Administrador";
                            break;
                    }

                    Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(
                        new FormsAuthenticationTicket(1, usuario.Login, DateTime.Now, DateTime.Now.AddMinutes(15), false, 
                            roles))));

                    Session["Usuario"] = usuario;

                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            return View(model);
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

        public ActionResult Criar()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Criar(CriarContaViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    Servicos.Usuario.CriarConta(model);
                    return RedirectToAction("Index", "Home");
                }
                catch (StorytellingException ex)
                {
                    TempData["MensagemExcecao"] = ex.Message;
                }
            }

            return View(model);
        }

        //
        // GET: /Account/ChangePassword

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(MudarSenhaViewModel model)
        {
            if (ModelState.IsValid)
            {
                if (Servicos.Usuario.MudarSenha(model, User.Identity.Name))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }              
            }

            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }
    }
}
